package com.lhdx.practical.controllers;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lhdx.practical.bean.*;
import com.lhdx.practical.dao.MenuDao;
import com.lhdx.practical.excelBean.ExcelFraction;
import com.lhdx.practical.service.*;
import com.lhdx.practical.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/function/fraction")
public class FractionController {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private FractionService fractionService;
    @Autowired
    private ContentService contentService;
    @Autowired
    private PersonService personService;
    @Autowired
    private MenuDao menuDao;
    @Autowired
    private StudentGroupService studentGroupService;
    @Autowired
    private PerformanceService performanceService;

    /**
     * 学生互评列表
     * @param mid
     * @param sid
     * @return
     */
    @GetMapping("/evaluation")
    public ModelAndView evaluation(long mid,long sid,long gradeid) {
        Menu menu = menuDao.findById(mid);
        Menu smenu = menuDao.findById(sid);
        Content content = contentService.findByGradeidAndSid(gradeid,sid);
        long userid = Long.parseLong(CookieUtils.getCookieByNameValue(request, Constants.LOGINED));
        Person person = personService.findById(userid);
        List<Person> personList = null;
        JSONArray array = new JSONArray();
        JSONObject obj = null;
        Fraction fraction = null;
        if(person.getGroupid() != 0){
            personList = personService.findByGroupid(person.getGroupid());
            for(Person p : personList){
                obj = new JSONObject();
                obj.put("id",p.getId()+"");
                obj.put("groupid",p.getGroupid()+"");
                obj.put("realname",p.getRealname());
                fraction = fractionService.findByPersonidAndSidAndAuthorid(p.getId(),sid,userid);
                if(fraction != null){
                    obj.put("score",fraction.getScoring());
                }else{
                    obj.put("score",0);
                }
                array.add(obj);
            }
        }

        return new ModelAndView("fraction/evaluation")
                .addObject("menu",menu)
                .addObject("smenu",smenu)
                .addObject("content",content)
                .addObject("personList",array)
                .addObject("person",person);
    }

    /**
     * 老师评价列表
     * @param mid
     * @param sid
     * @return
     */
    @GetMapping("/evaluate")
    public ModelAndView evaluate(long mid,long sid,long gradeid) {
        Menu menu = menuDao.findById(mid);
        Menu smenu = menuDao.findById(sid);
        int page = StrUtils.getInt(request,"p",1);
        Map<String,String> searchmap = new HashMap<>();
        searchmap.put("mid",mid+"");
        searchmap.put("sid",sid+"");
        searchmap.put("gradeid",gradeid+"");
        PageVo<Person> pageResult = new PageVo<Person>(page,searchmap,personService.getResultList(gradeid,0,2,page,Constants.pagesize));
        JSONArray array = new JSONArray();
        JSONObject object = null;
        JSONObject json = null;
        for(Person p : pageResult.getList()){
            object = new JSONObject();
            object.put("id",p.getId());
            object.put("groupname",p.getGroupname());
            object.put("name",p.getRealname());
            json = this.getAverage(p,mid);
            object.put("score",json.getString("score"));
            object.put("scoreStr",json.getString("scoreStr"));
            object.put("teacherScore",json.getString("teacherScore"));
            array.add(object);
        }
        return new ModelAndView("fraction/evaluate")
                .addObject("menu",menu)
                .addObject("smenu",smenu)
                .addObject("gradeid",gradeid)
                .addObject("arraylist",array)
                .addObject("pageResult",pageResult)
                ;
    }

    /**
     * 单元成绩上传
     * @param mid
     * @param sid
     * @return
     */
    @GetMapping("/performance")
    public ModelAndView performance(long mid,long sid,long gradeid) {
        Menu menu = menuDao.findById(mid);
        Menu smenu = menuDao.findById(sid);
        int page = StrUtils.getInt(request,"p",1);
        Map<String,String> searchmap = new HashMap<>();
        searchmap.put("mid",mid+"");
        searchmap.put("sid",sid+"");
        searchmap.put("gradeid",gradeid+"");
        PageVo<Person> pageResult = new PageVo<Person>(page,searchmap,personService.getResultList(gradeid,0,2,page,Constants.pagesize));
        JSONArray array = new JSONArray();
        JSONObject object = null;
        Performance performance = null;
        for(Person p : pageResult.getList()){
            object = new JSONObject();
            object.put("id",p.getId());
            object.put("groupname",p.getGroupname());
            object.put("name",p.getRealname());
            object.put("userno",p.getUserno());
            performance = performanceService.findByPersonidAndMid(p.getId(),mid);
            if(performance != null){
                object.put("groupscore",performance.getGroupscore());
                object.put("totalscore",performance.getTotalscore());
                object.put("personscore",performance.getPersonscore());
                object.put("usualscore",performance.getUsualscore());
            }else{
                JSONObject json = this.getAverage(p,mid);
                object.put("groupscore",0);
                object.put("totalscore",json.getString("score"));
                object.put("personscore",0);
                object.put("usualscore",0);
            }

            array.add(object);
        }
        return new ModelAndView("fraction/performance")
                .addObject("menu",menu)
                .addObject("smenu",smenu)
                .addObject("arraylist",array)
                .addObject("pageResult",pageResult)
                ;
    }


    /**
     * 成绩汇总
     * @param mid
     * @param sid
     * @param gradeid
     * @return
     */
    @GetMapping("/summary")
    public ModelAndView summary(long mid,long sid,long gradeid) {
        int page = StrUtils.getInt(request,"p",1);
        Map<String,String> searchmap = new HashMap<>();
        searchmap.put("mid",mid+"");
        searchmap.put("sid",sid+"");
        searchmap.put("gradeid",gradeid+"");
        PageVo<Person> pageResult = new PageVo<Person>(page,searchmap,personService.getResultList(gradeid,0,2,page,Constants.pagesize));
        JSONArray array = new JSONArray();
        JSONObject object = null;
        List<Performance> performanceList = null;
        for(Person p : pageResult.getList()){
            object = new JSONObject();
            object.put("id",p.getId());
            object.put("groupname",p.getGroupname());
            object.put("name",p.getRealname());
            object.put("userno",p.getUserno());
            performanceList = performanceService.findAllByPersonidAndGradeid(p.getId(),gradeid);
            if(performanceList.size() > 0){
                double groupscore = 0;
                double totalscore = 0;
                double personscore = 0;
                double usualscore = 0;
                for(Performance per : performanceList){
                    groupscore += per.getGroupscore();
                    totalscore += per.getTotalscore();
                    personscore += per.getPersonscore();
                    usualscore += per.getUsualscore();
                }
                if(groupscore != 0){
                    groupscore = groupscore/performanceList.size();
                }
                if(totalscore != 0){
                    totalscore = totalscore/performanceList.size();
                }
                if(personscore != 0){
                    personscore = personscore/performanceList.size();
                }
                if(usualscore != 0){
                    usualscore = usualscore/performanceList.size();
                }

                object.put("groupscore",groupscore);
                object.put("totalscore",totalscore);
                object.put("personscore",personscore);
                object.put("usualscore",usualscore);
            }else{
                JSONObject json = this.getAverage(p,mid);
                object.put("groupscore",0);
                object.put("totalscore",json.getString("score"));
                object.put("personscore",0);
                object.put("usualscore",0);
            }

            array.add(object);
        }
        return new ModelAndView("fraction/summary")
                .addObject("arraylist",array)
                .addObject("pageResult",pageResult);
    }

    /**
     * Excel导入成绩信息
     * @return
     */
    @CrossOrigin
    @PostMapping("/importAchievement")
    @ResponseBody
    public String importAchievement(@RequestParam(value="file", required=false) MultipartFile file,long mid) {
        JSONObject jsonObject = new JSONObject();
        try {
            if (file != null && !file.isEmpty()) {
                if(file.getContentType().equals("application/vnd.ms-excel")){
                    List<ExcelFraction> results = ExcelUtils.importExcel(file,1,1, ExcelFraction.class);
                    Performance performance = null;
                    BigDecimal b = null;
                    for(ExcelFraction ef : results){
                        performance = performanceService.findByPersonidAndMid(ef.getId(),mid);
                        if(performance != null){
                            performance.setTotalscore(Double.parseDouble(ef.getTotalscore()));
                            performance.setPersonscore(Double.parseDouble(ef.getPersonscore()));
                            performance.setUsualscore(Double.parseDouble(ef.getUsualscore()));
                            double gs = (performance.getTotalscore()+performance.getPersonscore()+performance.getUsualscore())/3;
                            b = new BigDecimal(gs);
                            performance.setGroupscore(b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                            performanceService.save(performance);
                        }
                    }
                    jsonObject = JsonUtils.JsonReturn(Constants.SUCCESS,"导入成功","");
                }else{
                    jsonObject = JsonUtils.JsonReturn(Constants.ERROR,"仅支持模版Excel文件","");
                }

            }else{
                jsonObject = JsonUtils.JsonReturn(Constants.ERROR,"请选择文件","");
            }
        }catch (Exception e) {
            e.printStackTrace();
            jsonObject = JsonUtils.JsonReturn(Constants.ERROR,"信息导入失败","");
        }
        return jsonObject.toString();
    }

    /**
     * 导出excel
     * @return
     */
    @CrossOrigin
    @RequestMapping(value = "/exportScoreExcel", method = { RequestMethod.POST, RequestMethod.GET })
    @ResponseBody
    public String exportExcel(HttpServletResponse response,long mid,long sid,long gradeid) {
        try{
            List<Person> personList = personService.findAllByTypeAndGradeid(2,gradeid);
            List<ExcelFraction> results = new ArrayList<>();
            ExcelFraction fraction = null;
            String totalscore = "";
            Performance performance = null;
            for(Person person : personList){
                fraction = new ExcelFraction();
                fraction.setId(person.getId());
                fraction.setGroupname(person.getGroupname());
                fraction.setName(person.getRealname());
                fraction.setUserno(person.getUserno());
                totalscore = this.getAverage(person,mid).getString("score");
                fraction.setTotalscore(totalscore);
                fraction.setPersonscore("0");
                fraction.setUsualscore("0");
                //fraction.setGroupscore("0");
                results.add(fraction);
                //导出同时 添加分数数据库
                performance = performanceService.findByPersonidAndMid(person.getId(),mid);
                if(performance == null){
                    performance = new Performance(mid,sid,person,Double.parseDouble(totalscore),0,0,0);
                }else{
                    performance.setTotalscore(Double.parseDouble(totalscore));
                }
                performanceService.save(performance);
            }
            ExcelUtils.exportExcel(results,"团队贡献评分","sheet1", ExcelFraction.class,"团队贡献评分导出.xls",response,request);
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    private JSONObject getAverage(Person p,long mid){
        JSONObject object = new JSONObject();
        List<Fraction> fractions = fractionService.findAllByPersonidAndGroupidAndMid(p.getId(),p.getGroupid(),mid);
        int score = 0;
        double average = 0;
        String scoreStr = "";
        double teacherScore = 0;
        if(fractions.size() > 0){
            for(Fraction f : fractions){
                score += f.getScoring();
                scoreStr += f.getScoring() + ",";
                teacherScore = f.getTeacherscore();
            }
            if(teacherScore != 0){
                average = teacherScore;
            }else{
                average = Double.parseDouble(score+"")/fractions.size();
            }

            scoreStr = scoreStr.substring(0,scoreStr.length()-1);
        }
        object.put("score",average);                //平均分
        object.put("scoreStr",scoreStr);            //互评分数
        object.put("teacherScore",teacherScore);    //老师打分
        return object;
    }

    /**
     * 学生互评
     * @param evaluation 拼接字符串 personid-groupid-分数
     * @return
     */
    @CrossOrigin
    @PostMapping("addEvaluation")
    @ResponseBody
    public String addEvaluation(long mid,long sid,String evaluation,long groupid) {
        JSONObject jsonObject = new JSONObject();
        try {
            long userid = Long.parseLong(CookieUtils.getCookieByNameValue(request, Constants.LOGINED));
            Person person = personService.findById(userid);
            List<Fraction> fractions = fractionService.findAllByAuthoridAndGroupidAndSid(person.getId(),groupid,sid);
            if(fractions.size() > 0){
                jsonObject = JsonUtils.JsonReturn(Constants.ERROR,"您已提交过评分","");
            }else{
                StudentGroup group = studentGroupService.findById(groupid);
                if(group.getState() != 2){
                    jsonObject = JsonUtils.JsonReturn(Constants.ERROR,"小组尚未审核通过，无法评分","");
                }else{
                    if(person.getType() == 2){
                        Fraction fraction = null;
                        if(evaluation.indexOf(",") == -1){
                            //小组单人情况下
                            String[] evals = evaluation.split("-");
                            fraction = new Fraction(0,mid,sid,Long.parseLong(evals[0]),person.getId(),Long.parseLong(evals[1]),evals[2],Integer.parseInt(evals[3]));
                            fractionService.save(fraction);
                        }else{
                            String[] strs = evaluation.split(",");
                            for(int i=0;i<strs.length;i++){
                                String[] evals = strs[i].split("-");
                                fraction = new Fraction(0,mid,sid,Long.parseLong(evals[0]),person.getId(),Long.parseLong(evals[1]),evals[2],Integer.parseInt(evals[3]));
                                fractionService.save(fraction);
                            }
                        }
                        jsonObject = JsonUtils.JsonReturn(Constants.SUCCESS,"打分成功","");
                    }else{
                        jsonObject = JsonUtils.JsonReturn(Constants.ERROR,"验证失败","");
                    }
                }
            }
        }catch (Exception e) {
            e.printStackTrace();
            jsonObject = JsonUtils.JsonReturn(Constants.ERROR,"打分失败","");
        }
        return jsonObject.toString();
    }

    /**
     * 老师修改分数
     * @return
     */
    @CrossOrigin
    @PostMapping("updateTeacherScore")
    @ResponseBody
    public String updateTeacherScore(long id,double score,long sid) {
        JSONObject jsonObject = new JSONObject();
        try {
            fractionService.updateTeacherScore(id,score,sid);
            jsonObject = JsonUtils.JsonReturn(Constants.SUCCESS,"修改成功","");
        }catch (Exception e) {
            e.printStackTrace();
            jsonObject = JsonUtils.JsonReturn(Constants.ERROR,"修改失败","");
        }
        return jsonObject.toString();
    }
}
